﻿//
// Copyright (c) 2024 BPer
//
#include <bperaudiodev/android/BPerAudioPlayAndroid.h>
#include <bperutil/BPerautofree.h>
#include <bperutil/sys/BPerLog.h>
#if BPer_OS_ANDROID

BPerAudioPlayAndroid::BPerAudioPlayAndroid(BPerAVInfo* avinfo,BPerSynBufferManager* streams):BPerAudioPlay(avinfo,streams){
	m_audioAndroid=(BPerAudioAndroid*)calloc(sizeof(BPerAudioAndroid),1);

	m_loops = 0;
	m_frames = 0;
	m_isStart = 0;
	m_isInit = 0;
}

BPerAudioPlayAndroid::~BPerAudioPlayAndroid() {
	closeAudio();
}

int BPerAudioPlayAndroid::init() {
	if (m_isInit == 1)
		return BPer_Ok;

	m_frames = m_avinfo->audio.sample / 50;
	if(bPer_create_audioAndroid_play(m_audioAndroid, m_avinfo->audio.sample,m_avinfo->audio.channel)!=BPer_Ok){
		return bPer_error_wrap(ERROR_SYS_AudioRender,"init android play fail");
	}
	uint32_t val = 0;
	int32_t dir = 0;

	m_audioData.initRender(m_sample,m_channel);
	m_isInit = 1;
	return BPer_Ok;

}

void BPerAudioPlayAndroid::closeAudio() {

	bPer_destroy_audioAndroid(m_audioAndroid);
	bPer_free(m_audioAndroid);

}

void BPerAudioPlayAndroid::stopLoop() {
	m_loops = 0;
}

void BPerAudioPlayAndroid::startLoop() {
	if(m_isInit==0) return;
	m_loops = 1;
	unsigned long status = 0;
	uint8_t *pcm = new uint8_t[4096*2];
	memset(pcm,0,4096*2);
	BPerAutoFreeA(uint8_t,pcm);

	BPerFrame frame;
	memset(&frame,0,sizeof(BPerFrame));
	int err = 0;
	uint8_t* tmp=NULL;

	int32_t audiolen = m_frames * m_channel * 2;
	while (m_loops == 1) {

		if(m_audioAndroid==NULL||m_audioAndroid->getInputdataCount(m_audioAndroid->context)!=0) {
			usleep(1000);
			continue;
		}

			tmp =m_audioData.getRenderAudioData(audiolen);

			if (tmp){
				m_audioAndroid->audioOut(m_audioAndroid->context,(uint16_t*)tmp,audiolen);
			}else{
				m_audioAndroid->audioOut(m_audioAndroid->context,(uint16_t*)pcm,audiolen);
			}
	}
}
#endif

